const pool = require('../config/db');

/**
 * 获取指定酒店的房间列表
 * @param {number} storeId - 酒店店铺ID
 * @returns {Promise<Array>} - 房间列表
 */
const getRoomsByStoreId = async (storeId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT * FROM hotel_rooms 
             WHERE store_id = ? 
             ORDER BY price ASC`,
            [storeId]
        );
        return rows;
    } catch (error) {
        console.error('[MODEL] 获取酒店房间列表失败:', error);
        throw error;
    }
};

/**
 * 获取指定房间详情
 * @param {number} roomId - 房间ID
 * @returns {Promise<Object>} - 房间详情
 */
const getRoomById = async (roomId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT * FROM hotel_rooms 
             WHERE id = ?`,
            [roomId]
        );
        return rows[0];
    } catch (error) {
        console.error('[MODEL] 获取房间详情失败:', error);
        throw error;
    }
};

/**
 * 添加酒店房间
 * @param {Object} roomData - 房间数据
 * @returns {Promise<number>} - 新房间ID
 */
const addRoom = async (roomData) => {
    try {
        const {
            store_id,
            name,
            description,
            price,
            discount_price,
            capacity,
            amenities,
            images,
            status
        } = roomData;

        const [result] = await pool.execute(
            `INSERT INTO hotel_rooms 
             (store_id, name, description, price, discount_price, capacity, amenities, images, status) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [store_id, name, description, price, discount_price, capacity, JSON.stringify(amenities), JSON.stringify(images), status]
        );

        return result.insertId;
    } catch (error) {
        console.error('[MODEL] 添加酒店房间失败:', error);
        throw error;
    }
};

/**
 * 更新酒店房间信息
 * @param {number} roomId - 房间ID
 * @param {Object} roomData - 房间数据
 * @returns {Promise<boolean>} - 更新成功返回true
 */
const updateRoom = async (roomId, roomData) => {
    try {
        const {
            name,
            description,
            price,
            discount_price,
            capacity,
            amenities,
            images,
            status
        } = roomData;

        await pool.execute(
            `UPDATE hotel_rooms 
             SET name = ?, 
                 description = ?, 
                 price = ?, 
                 discount_price = ?, 
                 capacity = ?, 
                 amenities = ?, 
                 images = ?, 
                 status = ?,
                 updated_at = CURRENT_TIMESTAMP
             WHERE id = ?`,
            [name, description, price, discount_price, capacity, JSON.stringify(amenities), JSON.stringify(images), status, roomId]
        );

        return true;
    } catch (error) {
        console.error('[MODEL] 更新酒店房间失败:', error);
        throw error;
    }
};

/**
 * 删除酒店房间
 * @param {number} roomId - 房间ID
 * @returns {Promise<boolean>} - 删除成功返回true
 */
const deleteRoom = async (roomId) => {
    try {
        await pool.execute(
            `DELETE FROM hotel_rooms WHERE id = ?`,
            [roomId]
        );
        return true;
    } catch (error) {
        console.error('[MODEL] 删除酒店房间失败:', error);
        throw error;
    }
};

/**
 * 检查房间是否可预订
 * @param {number} roomId - 房间ID
 * @param {string} checkInDate - 入住日期
 * @param {string} checkOutDate - 退房日期
 * @returns {Promise<boolean>} - 可预订返回true
 */
const checkRoomAvailability = async (roomId, checkInDate, checkOutDate) => {
    try {
        // 查询指定日期范围内是否有预订
        const [rows] = await pool.execute(
            `SELECT COUNT(*) as count 
             FROM room_bookings 
             WHERE room_id = ? 
             AND (
                 (check_in_date <= ? AND check_out_date >= ?) OR
                 (check_in_date <= ? AND check_out_date >= ?) OR
                 (check_in_date >= ? AND check_out_date <= ?)
             )`,
            [roomId, checkInDate, checkInDate, checkOutDate, checkOutDate, checkInDate, checkOutDate]
        );

        return rows[0].count === 0;
    } catch (error) {
        console.error('[MODEL] 检查房间可用性失败:', error);
        throw error;
    }
};

/**
 * 创建房间预订
 * @param {Object} bookingData - 预订数据
 * @returns {Promise<number>} - 预订ID
 */
const createBooking = async (bookingData) => {
    try {
        const {
            user_id,
            room_id,
            store_id,
            check_in_date,
            check_out_date,
            guest_name,
            guest_phone,
            price,
            deposit_amount,
            status
        } = bookingData;

        const [result] = await pool.execute(
            `INSERT INTO room_bookings 
             (user_id, room_id, store_id, check_in_date, check_out_date, guest_name, guest_phone, price, deposit_amount, status, created_at) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
            [user_id, room_id, store_id, check_in_date, check_out_date, guest_name, guest_phone, price, deposit_amount, status]
        );

        return result.insertId;
    } catch (error) {
        console.error('[MODEL] 创建房间预订失败:', error);
        throw error;
    }
};

/**
 * 获取用户的房间预订列表
 * @param {number} userId - 用户ID
 * @returns {Promise<Array>} - 预订列表
 */
const getUserBookings = async (userId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT rb.*, hr.name as room_name, hr.images as room_images, s.name as store_name, s.address as store_address
             FROM room_bookings rb
             JOIN hotel_rooms hr ON rb.room_id = hr.id
             JOIN stores s ON rb.store_id = s.id
             WHERE rb.user_id = ?
             ORDER BY rb.created_at DESC`,
            [userId]
        );
        return rows;
    } catch (error) {
        console.error('[MODEL] 获取用户房间预订列表失败:', error);
        throw error;
    }
};

/**
 * 获取店铺的房间预订列表
 * @param {number} storeId - 店铺ID
 * @returns {Promise<Array>} - 预订列表
 */
const getStoreBookings = async (storeId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT rb.*, hr.name as room_name, u.name as user_name, u.phone as user_phone
             FROM room_bookings rb
             JOIN hotel_rooms hr ON rb.room_id = hr.id
             JOIN users u ON rb.user_id = u.id
             WHERE rb.store_id = ?
             ORDER BY rb.created_at DESC`,
            [storeId]
        );
        return rows;
    } catch (error) {
        console.error('[MODEL] 获取店铺房间预订列表失败:', error);
        throw error;
    }
};

/**
 * 更新预订状态
 * @param {number} bookingId - 预订ID
 * @param {string} status - 新状态
 * @returns {Promise<boolean>} - 更新成功返回true
 */
const updateBookingStatus = async (bookingId, status) => {
    try {
        await pool.execute(
            `UPDATE room_bookings 
             SET status = ?, updated_at = CURRENT_TIMESTAMP
             WHERE id = ?`,
            [status, bookingId]
        );
        return true;
    } catch (error) {
        console.error('[MODEL] 更新预订状态失败:', error);
        throw error;
    }
};

module.exports = {
    getRoomsByStoreId,
    getRoomById,
    addRoom,
    updateRoom,
    deleteRoom,
    checkRoomAvailability,
    createBooking,
    getUserBookings,
    getStoreBookings,
    updateBookingStatus
}; 